import React, { Component, ComponentClass } from 'react';
import {View, Navigator} from '@tarojs/components'
import {connect} from 'react-redux'
import {CityLocation, RecommendGood} from '../../utils/server.interface'
import GoodShow from '../../components/good-show/good-show'
import {http} from '../../utils/http'
import {RECOMMEND_PAGE} from '../../constants/api'
import {vcmonitor} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import './recommend-list.scss'

type PageStateProps = {
  location: CityLocation
}
type PageDispatchProps = {}
type PageOwnProps = {}
type PageState = {}
type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface RecommendList {
  props: IProps
}

@connect(({location}) => ({
  location
}), (dispatch) => ({}))

class RecommendList extends Component {
  state: {
    goods: RecommendGood[]
    loadMoreStatus: "more" | "loading" | "noMore"
  } = {
    goods: [],
    loadMoreStatus: 'loading'
  }
  page = 1
  sid = ''

  async componentDidShow() {
    vcmonitor(this)
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    if (Taro.getCurrentInstance().router.params.sid) {
      this.sid = Taro.getCurrentInstance().router.params.sid
    }
    const goods = await this.getGoods(this.page);
    this.setState({goods})
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      const old = this.state.goods;
      const newData = await this.getGoods(this.page + 1);
      this.setState({goods: [...old, ...newData]})
    }
  }

  async getGoods(page = 1) {
    const goodsData = await http.get<RecommendGood[]>(RECOMMEND_PAGE, {
      p: page,
      areaId: this.props.location.region_id,
      sid: this.sid
    })
    if (goodsData) {
      if (goodsData.length === 10) {
        this.setState({loadMoreStatus: 'more'})
      } else {
        this.setState({loadMoreStatus: 'noMore'})
      }
      return goodsData
    } else {
      this.setState({loadMoreStatus: 'noMore'})
      return []
    }
  }

  render() {
    const {goods, loadMoreStatus} = this.state
    return (
      <View className='recommend-list-root'>
        <GzhAuth />
        {goods.map(item => <Navigator className='good-item' url='' key={item.id} hoverClass='none'>
          <GoodShow image={item.img} title={item.name} price={item.price} markPrice={item.market_price} />
        </Navigator>)}
      </View>
    )
  }
}

export default RecommendList as ComponentClass<PageOwnProps, PageState>
